import { Request, Response, NextFunction } from "express";
import { connection } from "@/services/database";
import { generateUpdateFields, checkIsSignupBelongUser, checkIsAdmin } from "@/utils/sql";

interface Params {
	signup_id: number;
	parent_phone_number?: string;
	origin?: string;
	party_affiliation?: "中共党员/预备党员" | "共青团员" | "群众";
	major?: string;
	awards?: string;
	personal_evaluation?: string;
	personal_intentions?: string;
}
export default async (request: Request, response: Response, next: NextFunction) => {
	try {
		const callerId = response.locals.user.id;
		const params = request.body as unknown as Params;
		if (!(await checkIsSignupBelongUser(callerId, params.signup_id)) && !(await checkIsAdmin(callerId))) throw new Error("无权操作");
		(await connection.execute(
			"UPDATE signup SET " +
				generateUpdateFields({
					parent_phone_number: params.parent_phone_number,
					origin: params.origin,
					party_affiliation: params.party_affiliation,
					major: params.major,
					awards: params.awards,
					personal_evaluation: params.personal_evaluation,
					personal_intentions: params.personal_intentions,
				}) +
				" WHERE signup_id = :signup_id",
			params
		)) as any;
		response.json({ data: null, message: "成功" });
	} catch (error) {
		response.statusCode = 400;
		next(error);
	}
};
